package org.water.common.shiro;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.water.common.param.AppSysParam;
import org.water.common.util.CookieUtils;
import org.water.sys.entity.SysUser;

/**
 * 操作cookie
 * @author qzy
 *
 */
public class UserCookie {

	private static int timeOut=30*24*60*60;
	/**
	 * 设置用户cookie
	 * @param request
	 * @param response
	 */
	public static void setUserCookie(SysUser user,HttpServletRequest request,HttpServletResponse response)
	{
		String rememberMe=request.getParameter("rememberMe");
		if("true".equalsIgnoreCase(rememberMe))
		{
			String pwd="";
			if(user.getPassword().length()!=32)
			{
				pwd=ShiroPwdHelper.getEncodePWD(user.getPassword(), user.getUserName()+AppSysParam.USER_AES_KEY);
			}
			else
			{
				pwd=user.getPassword();
			}
			CookieUtils.addCookie(response, "bweb_rememberMe", rememberMe, timeOut, true, false);
			CookieUtils.addCookie(response, "bweb_username", user.getUserName(), timeOut, true, false);
			CookieUtils.addCookie(response, "bweb_pwd", pwd, timeOut, true, false);
	        //response.addCookie(getCookie("bweb_rememberMe",rememberMe,timeOut));
	       // response.addCookie(getCookie("bweb_username",user.getUserName(),timeOut));
	       // response.addCookie(getCookie("bweb_pwd",pwd,timeOut));
		}
		else
		{
			CookieUtils.addCookie(response, "bweb_rememberMe", "false", timeOut, true, false);
			CookieUtils.addCookie(response, "bweb_username", "", timeOut, true, false);
			CookieUtils.addCookie(response, "bweb_pwd", "", timeOut, true, false);
			//response.addCookie(getCookie("bweb_rememberMe","false",timeOut));
	        //response.addCookie(getCookie("bweb_username","",timeOut));
	        //response.addCookie(getCookie("bweb_pwd","",timeOut));
		}
		//String httpOnly="HTTPOnly;";
		//response.setHeader("Set-Cookie", "cookiename=value;Path=/;Domain=domainvalue;Max-Age=seconds;HTTPOnly");
	}
	/**
	 * 获取cookie
	 * @param name
	 * @param value
	 * @param time
	 * @return
	 */
	static Cookie getCookie(String name,String value,int time)
	{
		Cookie cookie=new Cookie(name, value);
		cookie.setMaxAge(time);
		return cookie;
	}
}
